package com.bootdo.common.utils;

import com.bootdo.elasticsearch.util.Conv;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日期处理
 */
public class DateUtils {
    /**
     * 时间格式(yyyy-MM-dd)
     */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /**
     * 时间格式(yyyy-MM-dd HH:mm:ss)
     */
    public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String SHORT_DATE_FORMAT_STR = "yyyy-MM-dd";
    public static final String LONG_DATE_FORMAT_STR = "yyyy-MM-dd HH:mm:ss";
    public static final String LONG_FORMAT_YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
    public static final String MINUTE_DATE_FORMAT_STR = "yyyy-MM-dd HH:mm";
    public static final String SHORT_TIME_FORMAT_STR = "HH:mm:ss";
    public static final String MONTH_FORMAT_STR = "yyyy-MM";
    public static final String YEAR_FORMAT_STR = "yyyy";
    public static final DateFormat SHORT_DATE = new SimpleDateFormat(SHORT_DATE_FORMAT_STR);
    public static final DateFormat SHORT_DATE_FORMAT = new SimpleDateFormat(SHORT_DATE_FORMAT_STR);
    public static final DateFormat LONG_DATE_FORMAT = new SimpleDateFormat(LONG_DATE_FORMAT_STR);
    public static final DateFormat YEAR_DATE_FORMAT = new SimpleDateFormat(YEAR_FORMAT_STR);
    public static final String EARLY_TIME = "00:00:00";
    public static final String LATE_TIME = "23:59:59";
    public static final SimpleDateFormat FORMAT_TIME_NOZONE;
    private final static Logger logger = LoggerFactory.getLogger(DateUtils.class);

    private static final TimeZone TZ = TimeZone.getTimeZone("GMT+:08:00");
    private static final SimpleDateFormat FORMAT_DATE_TIME;
    private static final SimpleDateFormat FORMAT_TIME;
    private static final SimpleDateFormat FORMAT_DATE;
    private static final SimpleDateFormat FORMAT_MONTH_DATE;
    private static final SimpleDateFormat FORMAT_MONTH;
    private static final SimpleDateFormat FORMAT_DATE_NOZONE;
    private static final SimpleDateFormat FORMAT_DATE_TIME_NOZONE;
    private static final SimpleDateFormat FORMAT_YYYYMMDD;
    private static final SimpleDateFormat FORMAT_YYYYMMDDHHMMSS;
    private static final SimpleDateFormat FORMAT_DATE_TIME_CHINESE;
    private static final SimpleDateFormat FORMAT_DATE_CHINESE;
    private static final long ONE_MINUTE = 60000L;//create by dl
    private static final long ONE_HOUR = 3600000L;//create by dl
    private static final long ONE_DAY = 86400000L;//create by dl
    private static final long ONE_WEEK = 604800000L;//create by dl
    private static final String ONE_SECOND_AGO = "秒前";//create by dl
    private static final String ONE_MINUTE_AGO = "分钟前";//create by dl
    private static final String ONE_HOUR_AGO = "小时前";//create by dl
    private static final String ONE_DAY_AGO = "天前";//create by dl
    private static final String ONE_WEEK_AGO = "周前";//create by dl
    private static final String ONE_MONTH_AGO = "月前";//create by dl
    private static final String ONE_YEAR_AGO = "年前";//create by dl

    static {
        FORMAT_DATE_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        FORMAT_DATE_TIME.setTimeZone(TZ);

        FORMAT_TIME = new SimpleDateFormat("HH:mm:ss");
        FORMAT_TIME.setTimeZone(TZ);

        FORMAT_TIME_NOZONE = new SimpleDateFormat("HH:mm:ss");

        FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");
        // FORMAT_DATE.setTimeZone(TZ);

        FORMAT_MONTH_DATE = new SimpleDateFormat("yyyyMM");
        FORMAT_MONTH_DATE.setTimeZone(TZ);

        FORMAT_MONTH = new SimpleDateFormat("yyyy-MM");
        FORMAT_MONTH.setTimeZone(TZ);

        FORMAT_YYYYMMDD = new SimpleDateFormat("yyyyMMdd");
        FORMAT_YYYYMMDD.setTimeZone(TZ);

        FORMAT_YYYYMMDDHHMMSS = new SimpleDateFormat("yyyyMMddHHmmss");
        //FORMAT_YYYYMMDDHHMMSS.setTimeZone(TZ);

        FORMAT_DATE_TIME_CHINESE = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        FORMAT_DATE_CHINESE = new SimpleDateFormat("yyyy年MM月dd日");
        // FORMAT_DATE_TIME_CHINESE.setTimeZone(TZ);

        FORMAT_DATE_NOZONE = new SimpleDateFormat("yyyy-MM-dd");
        FORMAT_DATE_TIME_NOZONE = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }


    /**
     * 计算距离现在多久，非精确
     *
     * @param date
     * @return
     */
    public static String getTimeBefore(Date date) {
        Date now = new Date();
        long l = now.getTime() - date.getTime();
        long day = l / (24 * 60 * 60 * 1000);
        long hour = (l / (60 * 60 * 1000) - day * 24);
        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        String r = "";
        if (day > 0) {
            r += day + "天";
        } else if (hour > 0) {
            r += hour + "小时";
        } else if (min > 0) {
            r += min + "分";
        } else if (s > 0) {
            r += s + "秒";
        }
        r += "前";
        return r;
    }

    /**
     * 计算距离现在多久，精确
     *
     * @param date
     * @return
     */
    public static String getTimeBeforeAccurate(Date date) {
        Date now = new Date();
        long l = now.getTime() - date.getTime();
        long day = l / (24 * 60 * 60 * 1000);
        long hour = (l / (60 * 60 * 1000) - day * 24);
        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        String r = "";
        if (day > 0) {
            r += day + "天";
        }
        if (hour > 0) {
            r += hour + "小时";
        }
        if (min > 0) {
            r += min + "分";
        }
        if (s > 0) {
            r += s + "秒";
        }
        r += "前";
        return r;
    }

    /**
     * 格式化时间为yyyy-MM-dd HH:mm:ss，不设置时区
     */
    public static Date formatDateTimeNoZone(String str) {
        try {
            return FORMAT_DATE_TIME_NOZONE.parse(str);
        } catch (ParseException e) {
            return new Date();
        }
    }

    /**
     * 格式化时间为yyyy-MM-dd HH:mm:ss，不设置时区
     */
    public static String formatDateTimeNoZone(Date date) {
        try {
            return FORMAT_DATE_TIME_NOZONE.format(date);
        } catch (Exception e) {
            return FORMAT_DATE_TIME_NOZONE.format(new Date());
        }
    }

    /**
     * 获取当前月份时间
     */
    public static String getNowMonth() {
        String year_month =
                getYear(now()) + "-" + (getMonth(now()) + 1 >= 10 ? getMonth(now()) + 1 : "0" + (getMonth(now()) + 1));
        return year_month;
    }

    /**
     * 获取月份 num 0 当前月, 1前一个月
     *
     * @param num
     * @param format
     * @return
     */
    public static String getMonthStr(int num, String format) {
        LocalDate today = LocalDate.now();
        today = today.minusMonths(num);
        DateTimeFormatter formatters = DateTimeFormatter.ofPattern(format);
        return formatters.format(today);
    }

    /**
     * 获取当前月份时间
     */
    public static String getLastMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        Date date = calendar.getTime();
        return format(date, MONTH_FORMAT_STR);
    }

    /**
     * 2016-02-23 08:09:01
     */
    public static Timestamp fromPatter(String value, String patter, Timestamp defaultValue) {
        SimpleDateFormat sdf = new SimpleDateFormat(patter);
        try {
            return new Timestamp(sdf.parse(value).getTime());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Calendar getCalendar() {
        return Calendar.getInstance(TZ);
    }

    public static String toDateTimeStr(Date date) {
        return FORMAT_DATE_TIME.format(date);
    }

    public static String toTimeStr(Date date) {
        return FORMAT_TIME.format(date);
    }

    public static String toDateStr(Date date) {
        return FORMAT_DATE.format(date);
    }

    public static String toDateTimeStrNoLine(Date date) {
        return FORMAT_YYYYMMDDHHMMSS.format(date);
    }

    public static String toMonthStr(Date date) {
        return FORMAT_MONTH_DATE.format(date);
    }

    public static Integer toyyyyMMdd(Date date) {
        return Integer.parseInt(FORMAT_YYYYMMDD.format(date));
    }

    /**
     * 2016-02-23
     */
    public static Date fromDate(String v) {
        try {
            return FORMAT_DATE.parse(v);
        } catch (ParseException e) {
            return new Date();
        }
    }

    public static Date fromMonthDate(String dateStr) {
        try {
            return FORMAT_MONTH.parse(dateStr);
        } catch (ParseException e) {
            return new Date();
        }
    }

    /**
     * 字符串转时间
     */
    public static Date parseDate(String date, String pattern) {
        try {
            return new SimpleDateFormat(pattern).parse(date);
        } catch (ParseException e) {
            return new Date();
        }
    }

    /**
     * 获取日期的时间戳
     */
    public static long getTimeStamp(String str) {
        try {
            return FORMAT_DATE.parse(str).getTime();
        } catch (ParseException e) {
            return new Date().getTime();
        }
    }

    /**
     * 日期字符串转时间戳
     */
    public static Long string2Millis(String dateStr, String formatStr) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr);
            return simpleDateFormat.parse(dateStr).getTime();
        } catch (Exception e) {
            return 0L;
        }
    }


    /**
     * 20160223
     */
    public static Date fromDate(Integer vs) {
        try {
            String v = Integer.toString(vs);
            Calendar calc = getCalendar();
            calc.set(Calendar.YEAR, Integer.parseInt(v.substring(0, 4)));
            calc.set(Calendar.MONTH, Integer.parseInt(v.substring(4, 6)) - 1);
            calc.set(Calendar.DAY_OF_MONTH, Integer.parseInt(v.substring(6, 8)));

            calc.set(Calendar.HOUR_OF_DAY, 0);
            calc.set(Calendar.MINUTE, 0);
            calc.set(Calendar.SECOND, 0);
            return calc.getTime();

        } catch (Exception e) {
            return new Date();
        }
    }

    public static int getYear(Timestamp now) {
        Calendar calc = getCalendar();
        calc.setTime(new Date(now.getTime()));
        return calc.get(Calendar.YEAR);
    }

    public static int getYear(Date date) {
        Calendar calc = getCalendar();
        calc.setTime(date);
        return calc.get(Calendar.YEAR);
    }

    public static int getMonth(Timestamp now) {
        Calendar calc = getCalendar();
        calc.setTime(new Date(now.getTime()));
        return calc.get(Calendar.MONTH);
    }

    //月份是从0开始,这里加1
    public static int getMonth(Date date) {
        //Calendar calc = getCalendar();
        Calendar calc = Calendar.getInstance();
        calc.setTime(date);
        return (calc.get(Calendar.MONTH)) + 1;
    }

    public static int getDay(Timestamp now) {
        Calendar calc = getCalendar();
        calc.setTime(new Date(now.getTime()));
        return calc.get(Calendar.DAY_OF_MONTH);
    }

    public static int getDay(Date date) {
        //Calendar calc = getalendar();
        Calendar calc = Calendar.getInstance();
        calc.setTime(date);
        return (calc.get(Calendar.DAY_OF_MONTH));
    }

    /**
     * 2016-02-23 08:09:01
     */
    public static Date fromDateTime(String v) {
        try {
            return FORMAT_DATE_TIME.parse(v);
        } catch (ParseException e) {
            return new Date();
        }
    }

    /**
     * <pre>
     * 2016-02-23 return 2016-02-24
     * 2016-02-29 return 2016-03-01
     * </pre>
     */
    public static Date addDay(Date v, int days) {
        final Calendar calc = getCalendar();
        calc.setTime(v);
        calc.add(Calendar.DAY_OF_WEEK, days);
        return calc.getTime();
    }

    /**
     * 获取按天累加的日期序列
     */
    public static List<Date> getDaySeq(Date dt1, Date dt2) {
        final Calendar calc = getCalendar();

        List<Date> r = new ArrayList<>();
        for (calc.setTime(dt1); calc.getTime().compareTo(dt2) <= 0; calc.add(Calendar.DAY_OF_WEEK, 1)) {
            r.add(calc.getTime());
        }
        return r;
    }

    /**
     * <pre>
     * 获取按月累加的日期序列, 例如 201601 201702
     * 返回  201601 201602 201603
     * </pre>
     */
    public static List<String> getMonthSeq(int d1, int d2) {
        Date dt1 = fromDate(Integer.parseInt(Integer.toString(d1) + "01"));
        Date dt2 = fromDate(Integer.parseInt(Integer.toString(d2) + "01"));
        return getMonthSeq(dt1, dt2);
    }

    /**
     * 获取按月累加的日期序列, 返回 201601 201602 201603
     */
    public static List<String> getMonthSeq(Date dt1, Date dt2) {
        final Calendar calc = Calendar.getInstance();

        calc.setTime(dt1);
        if (calc.get(Calendar.DAY_OF_MONTH) > 1) {
            dt1 = fromDate(Integer.parseInt(toMonthStr(dt1).substring(0, 6) + "01"));
        }
        calc.setTime(dt2);
        if (calc.get(Calendar.DAY_OF_MONTH) > 1) {
            dt2 = fromDate(Integer.parseInt(toMonthStr(dt2).substring(0, 6) + "01"));
        }

        List<String> r = new ArrayList<>();
        for (calc.setTime(dt1); calc.getTime().compareTo(dt2) <= 0; calc.add(Calendar.MONTH, 1)) {
            r.add(toMonthStr(calc.getTime()));
        }
        return r;
    }

    public static void main(String[] args) throws Exception {

        // String format = DateUtils.format(new Date(), DateUtils.FORMAT_YYYYMMDDHHMMSS);

//    String format = FORMAT_YYYYMMDDHHMMSS.format(new Date());

        //   String format = DateUtils.format(new Date(), DateUtils.LONG_FORMAT_YYYYMMDDHHMMSS);

//    long timeStamp = getTimeStamp("2019-05-31 10:24:00");
//    long timeStamp2 = string2Millis("2019-05-31 10:24:11", DateUtils.MINUTE_DATE_FORMAT_STR);
//
//    System.out.println(timeStamp);
//    System.out.println(timeStamp2);
//
//    Map<String, List<String>> newHandleMap = new HashMap<>();
//    for (Map.Entry<String, List<String>> entry : newHandleMap.entrySet()) {
//      System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
//      String key = entry.getKey();
//
//    }
//    System.out.println(timeStamp);
//    System.out.println(timeStamp2);

        long l = subtractDay(DateUtils.fromDate("2019-08-01 00"), DateUtils.fromDate("2019-08-01"));
        System.out.println(l);

        System.out.println(DateUtils.getDayTimeByTimestamp("1578412800000"));
        Timestamp timestamp = new Timestamp(1578412800000L);
        System.out.println(DateUtils.toChineseFmt(timestamp));
        System.out.println(DateUtils.toChineseDateFmt(timestamp));

        Timestamp timestamp2 = new Timestamp(DateUtils.getTimeStamp("2020-04-26 16:41:11"));
        System.out.println("timestamp2->" + DateUtils.toChineseDateFmt(timestamp2));

    }

    /**
     * @param num   要获取二进制值的数
     * @param index 倒数第一位为0，依次类推
     * @return
     */
    public static int get(int num, int index) {
        return (num & (0x1 << index)) >> index;
    }


    public static Timestamp now() {
        return new Timestamp(System.currentTimeMillis());
    }

    public static int seconds(Timestamp t1, Timestamp t2) {
        return Conv.NI((t1.getTime() - t2.getTime()) / 1000);
    }

    public static Timestamp addSeconds(Timestamp t1, int seconds) {
        return new Timestamp(t1.getTime() + seconds * 1000);
    }

    /**
     * 用于设置后台搜索的时间项  返回精确到天
     */
    public static void setTime(Map map, String timeStr, String identify) {
        if (!StringUtils.isBlank(timeStr)) {
            String[] vs = timeStr.split("至");
            if (vs.length == 2) {
                Timestamp dt1 = new Timestamp(DateUtils.formatDateNoZone(vs[0].trim()).getTime());
                Timestamp dt2 = new Timestamp(DateUtils.addDay(DateUtils.formatDateNoZone(vs[1].trim()), 1).getTime());
                map.put(identify + "Begin", dt1);
                map.put(identify + "End", dt2);
            }
        }
    }

    /**
     * 用于设置后台搜索的时间项  返回精确到天
     */
    public static void setTime(Map map, String timeStr, String start, String end) {
        if (!StringUtils.isBlank(timeStr)) {
            String[] vs = timeStr.split("至");
            if (vs.length == 2) {
                Timestamp dt1 = new Timestamp(DateUtils.formatDateNoZone(vs[0].trim()).getTime());
                Timestamp dt2 = new Timestamp(DateUtils.addDay(DateUtils.formatDateNoZone(vs[1].trim()), 1).getTime());
                map.put(start, dt1);
                map.put(end, dt2);
            }
        }
    }

    /**
     * 格式化时间为yyyy-MM-dd，不设置时区
     */
    public static Date formatDateNoZone(String str) {
        try {
            if (!StringUtils.isNullOrEmpty(str)) {
                return FORMAT_DATE_NOZONE.parse(str);
            } else {
                return new Date();
            }
        } catch (ParseException e) {
            return new Date();
        }
    }

    public static String toChineseFmt(Timestamp startTime) {
        return FORMAT_DATE_TIME_CHINESE.format(new Date(startTime.getTime()));
    }

    public static String toChineseDateFmt(Timestamp startTime) {
        return FORMAT_DATE_CHINESE.format(new Date(startTime.getTime()));
    }

    /**
     * 使用参数Format格式化Date成字符串
     *
     * @return String
     */
    public static String format(Date date, String pattern) {
        return date == null ? "" : new SimpleDateFormat(pattern).format(date);
    }

    /**
     * 使用预设Format格式化Date成字符串
     *
     * @return String
     */
    public static String format(Date date) {
        return date == null ? "" : format(date, LONG_DATE_FORMAT_STR);
    }

    /**
     * 得到某个日期在这一天中时间最早的日期对象
     */

    public static Date getEarlyInTheDay(Date date) {
        String dateString = SHORT_DATE_FORMAT.format(date) + " " + EARLY_TIME;
        try {
            return LONG_DATE_FORMAT.parse(dateString);
        } catch (ParseException e) {
            throw new RuntimeException("parser date error.", e);
        }
    }

    /**
     * 没有秒的字符串得到含年月日时分秒格式的日期对象
     */
    public static String getLongTime(String date) {
        try {
            Date date1 = parseDate(date, DateUtils.MINUTE_DATE_FORMAT_STR);
            return LONG_DATE_FORMAT.format(date1);
        } catch (Exception e) {
            throw new RuntimeException("parser date error.", e);
        }
    }


    /**
     * 得到某个日期在这一天中时间最晚的日期对象
     */
    public static Date getLateInTheDay(Date date) {
        String dateString = SHORT_DATE_FORMAT.format(date) + " " + LATE_TIME;
        try {
            return LONG_DATE_FORMAT.parse(dateString);
        } catch (ParseException e) {
            throw new RuntimeException("parser date error.", e);
        }
    }

    /***
     * 将时间格式化为 yyyy-mm-dd的日期格式
     * @param date
     * @return
     */
    public static String getDateToString(Date date) {
        return SHORT_DATE.format(date);
    }

    /*
     * 获取前后日期 i为正数 向后推迟i天，负数时向前提前i天
     *
     * @author XP
     *
     * @time 2016年11月25日
     */
    public static Date getDate(int i) {
        Date dat = null;
        Calendar cd = Calendar.getInstance();
        cd.add(Calendar.DATE, i);
        dat = cd.getTime();
        SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp date = Timestamp.valueOf(dformat.format(dat));
        return date;
    }

    /*
     * 获取当前时间加或减一段时间以后的日期 , i为正数 向后推迟，负数时向前提前
     * @param i 增量, calendar 类型
     * @author XP
     * @time 2018年9月25日
     */
    public static Date getDate(int i, int calendar) {
        Date dat = null;
        Calendar cd = Calendar.getInstance();
        cd.add(calendar, i);
        dat = cd.getTime();
        SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp date = Timestamp.valueOf(dformat.format(dat));
        return date;
    }


    /*
     * 获取指定的时间加或减一段时间以后的日期 , i为正数 向后推迟，负数时向前提前
     * @param i 增量, calendar 类型
     * @author XP
     * @time 2016年11月25日
     */
    public static Date getDate(int i, int calendar, Date myDate) {
        Date dat = null;
        Calendar cd = Calendar.getInstance();
        cd.setTime(myDate);
        cd.add(calendar, i);
        dat = cd.getTime();
        SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp date = Timestamp.valueOf(dformat.format(dat));
        return date;
    }


    /**
     * 相差月份
     *
     * @param d1 endDate 被减的日期
     * @param d2 startDate 减去的日期
     */
    public static int subtractMonth(Date d1, Date d2) throws ParseException {
        Calendar c = Calendar.getInstance();
        c.setTime(d1);
        int year1 = c.get(Calendar.YEAR);
        int month1 = c.get(Calendar.MONTH);

        c.setTime(d2);
        int year2 = c.get(Calendar.YEAR);
        int month2 = c.get(Calendar.MONTH);

        int result;
        if (year1 == year2) {
            result = month1 - month2;
        } else {
            result = 12 * (year1 - year2) + month1 - month2;
        }
        return result;
    }

    /**
     * <br>
     * 第一个日期减去第二个日期后得到的天数</br>
     * <br>
     * 如果减去的后的天数有不满足一整天的，则不计入天数内</br>
     *
     * @param date  被减日期
     * @param other 减去的日期
     */
    public static long subtractDay(Date date, Date other) {
        return subtractSecond(date, other) / (24 * 60 * 60);
    }

    /**
     * 两个日期相减得到相差的毫秒数
     */
    public static long subtractSecond(Date date, Date other) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        long dateTimeInMillis = calendar.getTimeInMillis();
        Calendar otherCalendar = Calendar.getInstance();
        otherCalendar.setTime(other);
        long otherTimeInMillis = otherCalendar.getTimeInMillis();
        return (dateTimeInMillis - otherTimeInMillis) / (1000);
    }


    /**
     * date1比date2多的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        //不同年
        if (year1 != year2) {
            int timeDistance = 0;
            for (int i = year2; i < year1; i++) {
                //闰年
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    timeDistance += 366;
                } else {
                    //不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day1 - day2);
        } else {
            //同一年
            logger.info("判断day1 - day2 : " + (day1 - day2));
            return day1 - day2;
        }
    }

    /**
     * 两个字符串时间相减得到相差的秒数
     */
    public static int subtractSecond(String dateTime, String otherDateTime, String format) {
        if (StringUtils.isNullOrEmpty(dateTime) || StringUtils.isNullOrEmpty(otherDateTime)) {
            return 0;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(dateTime);
            Date otherDate = sdf.parse(otherDateTime);
            long subtractMillisecond = date.getTime() - otherDate.getTime();
            int subtractSecond = (int) (subtractMillisecond / 1000);
            return subtractSecond;
        } catch (Exception e) {
            return 0;
        }
    }

    public static int subtractSecond(String dateTime, String otherDateTime) {
        if (StringUtils.isNullOrEmpty(dateTime) || StringUtils.isNullOrEmpty(otherDateTime)) {
            return 0;
        }
        try {
            Date date = LONG_DATE_FORMAT.parse(dateTime);
            Date otherDate = LONG_DATE_FORMAT.parse(otherDateTime);
            long subtractMillisecond = date.getTime() - otherDate.getTime();
            int subtractSecond = (int) (subtractMillisecond / 1000);
            return subtractSecond;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * # 获取时间差天数
     *
     * @param dateTime
     * @param otherDateTime
     * @param format
     * @return
     * @Date 下午 18:51 2019/12/23 0023
     **/
    public static int subtractDay(String dateTime, String otherDateTime, String format) {
        if (StringUtils.isNullOrEmpty(dateTime) || StringUtils.isNullOrEmpty(otherDateTime)) {
            return 0;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(dateTime);
            Date otherDate = sdf.parse(otherDateTime);
            long subtractMillisecond = date.getTime() - otherDate.getTime();
            int subtractSecond = (int) (subtractMillisecond / 1000);
            return subtractSecond / (24 * 60 * 60);
        } catch (Exception e) {
            return 0;
        }
    }


    /**
     * 判断是否为yyyy-MM-dd格式字符串时间
     */
    public static boolean isShortDateFormatStr(String dateStr) {
        try {
            String regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}";
            Pattern pattern = Pattern.compile(regex);
            Matcher m = pattern.matcher(dateStr);
            boolean dateFlag = m.matches();
            if (!dateFlag) {
                return false;
            }
            DateFormat formatter = new SimpleDateFormat(SHORT_DATE_FORMAT_STR);
            formatter.setLenient(false);
            try {
                Date date = formatter.parse(dateStr);
                return true;
            } catch (Exception e) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断给定日期是否为当月第一天
     *
     * @return true:是|false:不是
     */
    public static boolean isFirstDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) + 0));
        if (calendar.get(Calendar.DAY_OF_MONTH) == 1) {
            return true;
        }
        return false;
    }

    /**
     * 获取指定年月的每天的日期
     *
     * @return List 格式 : "yyyy-mm-dd"
     */
    public static List<String> getDayListOfMonth(int year, int month) {
        List<String> list = new ArrayList();

        Calendar a = Calendar.getInstance();
        a.set(Calendar.YEAR, year);
        a.set(Calendar.MONTH, month - 1);
        a.set(Calendar.DATE, 1);// 把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);// 日期回滚一天，也就是最后一天
        int maxDate = a.get(Calendar.DATE);

        for (int i = 1; i <= maxDate; i++) {
            String dateStr = String.valueOf(year) + "-" + month + "-" + i;

            String formatStr = format(formatDateNoZone(dateStr), SHORT_DATE_FORMAT_STR);
            logger.info(formatStr);

            list.add(formatStr);
        }
        return list;
    }

    /**
     * 获取指定年月的第一天到指定天的日期List
     *
     * @return List 格式 : "yyyy-mm-dd"
     */
    public static List<String> getListFirstToCurrentDay(int year, int month, int day) {
        List<String> list = new ArrayList();
        for (int i = 1; i <= day; i++) {
            String dateStr = String.valueOf(year) + "-" + month + "-" + i;
            String formatStr = format(formatDateNoZone(dateStr), SHORT_DATE_FORMAT_STR);
            list.add(formatStr);
        }
        return list;
    }


    /**
     * 获得该月第一天
     */
    public static String getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最小天数
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = sdf.format(cal.getTime());
        return firstDayOfMonth;
    }

    /**
     * 获得该月最后一天
     */
    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }


    /**
     * 获取当前时间的流水号，格式：YYMMDDHHmmssSSS、年月日时分秒毫秒（年取后两位）
     */
    public static String getTimeFlowNumber() {
        return getTimeFlow().substring(2);
    }

    /**
     * 获取当前时间的流水号，格式：YYYYMMDDHHmmssSSS、年月日时分秒毫秒
     */
    public static String getTimeFlow() {
        StringBuffer sb = new StringBuffer();
        Calendar c = Calendar.getInstance();
        sb.append(c.get(Calendar.YEAR));
        sb.append(
                c.get(Calendar.MONTH) + 1 >= 10 ? "" + (c.get(Calendar.MONTH) + 1) : "0" + (c.get(Calendar.MONTH) + 1));
        sb.append(c.get(Calendar.DAY_OF_MONTH) >= 10 ?
                "" + c.get(Calendar.DAY_OF_MONTH) : "0" + c.get(Calendar.DAY_OF_MONTH));
        sb.append(c.get(Calendar.HOUR_OF_DAY) >= 10 ?
                "" + c.get(Calendar.HOUR_OF_DAY) : "0" + c.get(Calendar.HOUR_OF_DAY));
        sb.append(c.get(Calendar.MINUTE) >= 10 ? "" + c.get(Calendar.MINUTE) : "0" + c.get(Calendar.MINUTE));
        sb.append(c.get(Calendar.SECOND) >= 10 ? "" + c.get(Calendar.SECOND) : "0" + c.get(Calendar.SECOND));
        int millisecond = c.get(Calendar.MILLISECOND);
        if (millisecond < 10) {
            sb.append("00");
        } else if (millisecond >= 10 && millisecond < 100) {
            sb.append("0");
        }
        sb.append(millisecond);
        return sb.toString();
    }

    /**
     * 根据时间搓字符串得到当前时间
     *
     * @param timestampStr 时间戳字符串
     * @return String
     */
    public static String getDayTimeByTimestamp(String timestampStr) {
        if (StringUtils.isNullOrEmpty(timestampStr)) {
            return null;
        }
        Long timestamp = Long.parseLong(timestampStr);
        Date time = new Date(timestamp);
        return FORMAT_DATE_TIME_NOZONE.format(time);
    }

    /**
     * 验证时间格式
     */
    public static boolean isValidDate(String date, String format) {
        boolean flag = true;
        if (StringUtils.isNullOrEmpty(date)) {
            return false;
        }
        if (!StringUtils.isNullOrEmpty(date)) {
            try {
                if (SHORT_DATE_FORMAT_STR.equals(format)) {
                    if (!RegexUtils.checkByRegex(date, RegexUtils.DATE_REGEX)) {
                        return false;
                    }
                    FORMAT_DATE.parse(date);
                } else if (SHORT_TIME_FORMAT_STR.equals(format)) {
                    if (!RegexUtils.checkByRegex(date, RegexUtils.TIME_REGEX)) {
                        return false;
                    }
                    FORMAT_TIME_NOZONE.parse(date);
                } else if (MONTH_FORMAT_STR.equals(format)) {
                    if (!RegexUtils.checkByRegex(date, RegexUtils.MONTH_REGEX)) {
                        return false;
                    }
                    FORMAT_MONTH.parse(date);
                } else {
                    if (!RegexUtils.checkByRegex(date, RegexUtils.DATETIME_REGEX)) {
                        return false;
                    }
                    FORMAT_DATE_TIME_NOZONE.setLenient(false);
                    FORMAT_DATE_TIME_NOZONE.parse(date);
                }
            } catch (ParseException e) {
                flag = false;
            }
        }
        return flag;
    }


    /**
     * 验证时间格式
     *
     * @param date   要验证的时间
     * @param format 要验证的格式
     * @param min    要验证的最小值
     * @param max    要验证的最大值
     */
    public static boolean isValidDateFormat(String date, String format, int min, int max) {
        boolean flag = true;
        if (StringUtils.isNullOrEmpty(date)) {
            return false;
        }
        if (!StringUtils.isNullOrEmpty(date)) {
            try {
                if (SHORT_DATE_FORMAT_STR.equals(format)) {
                    FORMAT_DATE.parse(date);
                } else if (SHORT_TIME_FORMAT_STR.equals(format)) {
                    FORMAT_TIME_NOZONE.parse(date);

                    //格式验证通过以后, 验证最大最小值
                    int dateInt = Integer.parseInt(date.substring(0, 2));
                    if (!(dateInt >= min && dateInt < max)) {
                        flag = false;
                    }

                } else if (MONTH_FORMAT_STR.equals(format)) {
                    FORMAT_MONTH.parse(date);
                } else {
                    FORMAT_DATE_TIME_NOZONE.parse(date);
                }

            } catch (ParseException e) {
                flag = false;
            }
        }
        return flag;
    }


    /**
     * 验证时间格式
     */
    public static boolean isValidDateFormat(String date, String format) {
        boolean flag = true;
        if (StringUtils.isNullOrEmpty(date)) {
            return false;
        }
        if (!StringUtils.isNullOrEmpty(date)) {
            try {
                if (SHORT_DATE_FORMAT_STR.equals(format)) {
                    FORMAT_DATE.parse(date);
                } else if (SHORT_TIME_FORMAT_STR.equals(format)) {
                    FORMAT_TIME_NOZONE.parse(date);
                } else if (MONTH_FORMAT_STR.equals(format)) {
                    FORMAT_MONTH.parse(date);
                } else {
                    FORMAT_DATE_TIME_NOZONE.parse(date);
                }
            } catch (ParseException e) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 获取时间的字符串,不设置时区
     */
    public static String toDateTimeStrNoZone(Date date) {
        return FORMAT_DATE_TIME_NOZONE.format(date);
    }

    /**
     * 验证时间先后
     *
     * @param earlierTime 早一点的时间
     * @param laterTime   晚一点的时间
     * @param format      时间格式字符串
     * @ 当两个时间相等, 返回true
     */
    public static boolean checkTime(String earlierTime, String laterTime, String format) {
        boolean flag = false;
        if (!(StringUtils.isNullOrEmpty(earlierTime) || StringUtils.isNullOrEmpty(laterTime))) {
            if (laterTime.equals(earlierTime)) {
                return true;
            }
            try {
                if (SHORT_DATE_FORMAT_STR.equals(format)) {
                    Date earlier = FORMAT_DATE.parse(earlierTime);
                    Date later = FORMAT_DATE.parse(laterTime);
                    if (earlier.before(later)) {
                        return true;
                    }
                } else if (SHORT_TIME_FORMAT_STR.equals(format)) {
                    Date earlier = FORMAT_TIME_NOZONE.parse(earlierTime);
                    Date later = FORMAT_TIME_NOZONE.parse(laterTime);
                    if (earlier.before(later)) {
                        return true;
                    }
                } else if (MONTH_FORMAT_STR.equals(format)) {
                    Date earlier = FORMAT_MONTH.parse(earlierTime);
                    Date later = FORMAT_MONTH.parse(laterTime);
                    if (earlier.before(later)) {
                        return true;
                    }
                } else {
                    Date earlier = FORMAT_DATE_TIME_NOZONE.parse(earlierTime);
                    Date later = FORMAT_DATE_TIME_NOZONE.parse(laterTime);
                    if (earlier.before(later)) {
                        return true;
                    }
                }
            } catch (ParseException e) {
                flag = false;
            }
        }
        return flag;
    }


    /**
     * 验证时间先后
     *
     * @param earlierTime 早一点的时间
     * @param laterTime   晚一点的时间
     * @param format      时间格式字符串
     * @param tag         当两个时间相等时, 如果tag=true则返回true, 如果tag=false则返回false, 默认返回true
     */
    public static boolean checkTime(String earlierTime, String laterTime, String format, boolean tag) {
        boolean flag = false;
        if (!(StringUtils.isNullOrEmpty(earlierTime) || StringUtils.isNullOrEmpty(laterTime))) {
//      if (laterTime.equals(earlierTime)) {
//        return true;
//      }
            Date earlier = null;
            Date later = null;

            try {
                if (SHORT_DATE_FORMAT_STR.equals(format)) {
                    earlier = FORMAT_DATE.parse(earlierTime);
                    later = FORMAT_DATE.parse(laterTime);

                } else if (SHORT_TIME_FORMAT_STR.equals(format)) {
                    earlier = FORMAT_TIME_NOZONE.parse(earlierTime);
                    later = FORMAT_TIME_NOZONE.parse(laterTime);
                } else if (MONTH_FORMAT_STR.equals(format)) {
                    earlier = FORMAT_MONTH.parse(earlierTime);
                    later = FORMAT_MONTH.parse(laterTime);
                } else {
                    earlier = FORMAT_DATE_TIME_NOZONE.parse(earlierTime);
                    later = FORMAT_DATE_TIME_NOZONE.parse(laterTime);
                }

                //tag 当两个时间相等时, 如果tag=true则返回true, 如果tag=false则返回false
                if (tag) {
                    if (!earlier.after(later)) {
                        return true;
                    }
                } else {
                    if (earlier.before(later)) {
                        return true;
                    }
                }
            } catch (ParseException e) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 验证时间先后,相等时返回true
     *
     * @param earlierTime 早一点的时间
     * @param laterTime   晚一点的时间
     * @param format1     前一个时间的 时间格式字符串
     * @param format1     后一个时间的 时间格式字符串
     */

    public static boolean checkTime(String earlierTime, String format1, String laterTime, String format2) {
        boolean flag = false;
        if (!(StringUtils.isNullOrEmpty(earlierTime) || StringUtils.isNullOrEmpty(laterTime))) {
            if (laterTime.equals(earlierTime)) {
                return true;
            }

            try {

                Date earlier = null;
                Date later = null;

                //处理第一个时间
                if (SHORT_DATE_FORMAT_STR.equals(format1)) {
                    earlier = FORMAT_DATE.parse(earlierTime);
                } else if (SHORT_TIME_FORMAT_STR.equals(format1)) {
                    earlier = FORMAT_TIME_NOZONE.parse(earlierTime);
                } else if (MONTH_FORMAT_STR.equals(format1)) {
                    earlier = FORMAT_MONTH.parse(earlierTime);
                } else {
                    earlier = FORMAT_DATE_TIME_NOZONE.parse(earlierTime);
                }

                //处理第二个时间
                if (SHORT_DATE_FORMAT_STR.equals(format2)) {
                    later = FORMAT_DATE.parse(laterTime);
                } else if (SHORT_TIME_FORMAT_STR.equals(format2)) {
                    later = FORMAT_TIME_NOZONE.parse(laterTime);
                } else if (MONTH_FORMAT_STR.equals(format2)) {
                    later = FORMAT_MONTH.parse(laterTime);
                } else {
                    later = FORMAT_DATE_TIME_NOZONE.parse(laterTime);
                }

                if (!earlier.after(later)) {
                    return true;
                }

            } catch (ParseException e) {
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 获取当天0点0分0秒的日历
     */
    public static Calendar getDayCalender() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar;
    }

    /**
     * 获取本月第一天
     */
    public static String getFirstDayOfThisMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return format(calendar.getTime(), SHORT_DATE_FORMAT_STR);
    }

    /**
     * 获取本年第一天
     */
    public static String getFirstDayOfThisYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return format(calendar.getTime(), SHORT_DATE_FORMAT_STR);
    }

    /**
     * 获取本季度第一天
     */
    public static String getFirstDayOfThisQuarter(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH);
        if (month >= 0 && month <= 2) {
            calendar.set(Calendar.MONTH, 0);
        } else if (month > 2 && month <= 5) {
            calendar.set(Calendar.MONTH, 3);
        } else if (month > 5 && month <= 8) {
            calendar.set(Calendar.MONTH, 6);
        } else if (month > 8 && month <= 11) {
            calendar.set(Calendar.MONTH, 9);
        }
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return format(calendar.getTime(), SHORT_DATE_FORMAT_STR);
    }


    // 根据年月日计算年龄,birthTimeString:"1994-11-14"
    public static int getAgeFromBirthTime(String birthTimeString) {
        // 先截取到字符串中的年、月、日
        String strs[] = birthTimeString.trim().split("-");
        int selectYear = Integer.parseInt(strs[0]);
        int selectMonth = Integer.parseInt(strs[1]);
        int selectDay = Integer.parseInt(strs[2]);
        // 得到当前时间的年、月、日
        Calendar cal = Calendar.getInstance();
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayNow = cal.get(Calendar.DATE);

        // 用当前年月日减去生日年月日
        int yearMinus = yearNow - selectYear;
        int monthMinus = monthNow - selectMonth;
        int dayMinus = dayNow - selectDay;

        int age = yearMinus;// 先大致赋值
        if (yearMinus < 0) {// 选了未来的年份
            age = 0;
        } else if (yearMinus == 0) {// 同年的，要么为1，要么为0
            if (monthMinus < 0) {// 选了未来的月份
                age = 0;
            } else if (monthMinus == 0) {// 同月份的
                if (dayMinus < 0) {// 选了未来的日期
                    age = 0;
                } else if (dayMinus >= 0) {
                    age = 1;
                }
            } else if (monthMinus > 0) {
                age = 1;
            }
        } else if (yearMinus > 0) {
            if (monthMinus < 0) {// 当前月>生日月
            } else if (monthMinus == 0) {// 同月份的，再根据日期计算年龄
                if (dayMinus < 0) {
                } else if (dayMinus >= 0) {
                    age = age + 1;
                }
            } else if (monthMinus > 0) {
                age = age + 1;
            }
        }
        return age;
    }


    /**
     * 日期计算
     */
    public static int getAgeFromBirthTime(Date birthDay) throws ParseException {
        int age = 0;
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;//当前日期在生日之前，年龄减一
                }
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }


    /**
     * 根据日期字符串获取星期
     */
    public static String getDateWeek(String date) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(formatDateNoZone(date));
        return weekDays[calendar.get(Calendar.DAY_OF_WEEK) - 1];
    }

    /**
     * #获取日期的星期
     *
     * @Date 下午 15:59 2019/5/4 0004
     **/
    public static int getWeek(String date) {
        Calendar calendar = Calendar.getInstance();
        logger.info("需要转换的字符串:" + date);
        try {
            calendar.setTime(formatDateNoZone(date));
        } catch (Exception e) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date dateUtils;
            try {
                dateUtils = dateFormat.parse(date);
            } catch (ParseException ex) {
                dateUtils = new Date();
            }
            calendar.setTime(dateUtils);
        }
        return calendar.get(Calendar.DAY_OF_WEEK) - 1;
    }

    /**
     * 将 2016-08-15T16:00:00.000Z 时间格式转换成Date类型格式
     */
    public static Date tZtoDate(String time) throws Exception {
        if (StringUtils.isNullOrEmpty(time)) {
            return null;
        }
        time = time.replace("Z", " UTC");
        //System.out.println(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        Date date = format.parse(time);
        //System.out.println(date);
        return date;
    }

    /**
     * 将 2016-08-15T16:00:00.000Z 时间格式转换成 yyyy-MM-dd HH:mm:ss  类型格式
     */
    public static String tZtoDateStr(String time) throws Exception {
        if (StringUtils.isNullOrEmpty(time)) {
            return null;
        }
        time = time.replace("Z", " UTC");
        //System.out.println(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        Date date = format.parse(time);
        String dateStr = formatDateTimeNoZone(date);
        //System.out.println(date);
        return dateStr;
    }

    /**
     * createBy dl
     *
     * @param timeString 字符串时间
     * @param pattern    格式
     */
    public static Date parseTimeString2Date(String timeString, String pattern) {
        if ((timeString == null) || (timeString.equals(""))) {
            return null;
        }
        Date date = null;
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        try {
            date = new Date(dateFormat.parse(timeString).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String convertDate2String(Date date, String pattern) {
        if (date == null) {
            return null;
        }
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(date);
    }

    //获取年的数值
    public static int getYearValue(String timeString, String pattern) {
        String timeStr = convertDate2String(parseTimeString2Date(timeString, pattern), pattern);
        //System.out.println("getYearValue:" + timeStr);
        return Integer.parseInt(timeStr.substring(0, 4));
    }

    //获取月的数值
    public static int getMonthValue(String timeString, String pattern) {
        String timeStr = convertDate2String(parseTimeString2Date(timeString, pattern), pattern);
        //System.out.println("getMonthValue:" + timeStr);
        return Integer.parseInt(timeStr.substring(5, 7));
    }

    //获取天的数值
    public static int getDayValue(String timeString, String pattern) {
        String timeStr = convertDate2String(parseTimeString2Date(timeString, pattern), pattern);
        //System.out.println("getDayValue:" + timeStr);
        return Integer.parseInt(timeStr.substring(8, 10));
    }

    //获取时的数值
    public static int getHourValue(String timeString, String pattern) {
        String timeStr = convertDate2String(parseTimeString2Date(timeString, pattern), pattern);
        //System.out.println("getHourValue:" + timeStr);
        return Integer.parseInt(timeStr.substring(11, 13));
    }

    //获取分的数值
    public static int getMinuteValue(String timeString, String pattern) {
        String timeStr = convertDate2String(parseTimeString2Date(timeString, pattern), pattern);
        //System.out.println("getMinuteValue:" + timeStr);
        return Integer.parseInt(timeStr.substring(14, 16));
    }

    //获取秒的数值
    public static int getSecondValue(String timeString, String pattern) {
        String timeStr = convertDate2String(parseTimeString2Date(timeString, pattern), pattern);
        //System.out.println("getSecondValue:" + timeStr);
        return Integer.parseInt(timeStr.substring(17, 19));
    }

    /**
     * 转换时间为几秒前、几分钟前、半小时前、小时前、几天前、几周前、几月前、几年前
     *
     * @param date
     * @return
     */
    public static String relativeFormat(Date date) {
        long delta = new Date().getTime() - date.getTime();
        if (delta < 1L * ONE_MINUTE) {
            long seconds = toSeconds(delta);
            return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO;
        }
        if (delta < 30L * ONE_MINUTE) {
            long minutes = toMinutes(delta);
            return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO;
        }
        if (delta < 60L * ONE_MINUTE) {
            return "半" + ONE_HOUR_AGO;
        }
        if (delta < 24L * ONE_HOUR) {
            long hours = toHours(delta);
            return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO;
        }
        if (delta < 48L * ONE_HOUR) {
            return "昨天";
        }
        if (delta < 7L * ONE_DAY) {
            long days = toDays(delta);
            return (days <= 0 ? 1 : days) + ONE_DAY_AGO;
        }
        if (delta < 4L * ONE_WEEK) {
            long weeks = toWeeks(delta);
            return (weeks <= 0 ? 1 : weeks) + ONE_WEEK_AGO;
        }
        if (delta < 12L * 4L * ONE_WEEK) {
            long months = toMonths(delta);
            return (months <= 0 ? 1 : months) + ONE_MONTH_AGO;
        } else {
            long years = toYears(delta);
            return (years <= 0 ? 1 : years) + ONE_YEAR_AGO;
        }
    }

    private static long toSeconds(long date) {
        return date / 1000L;
    }

    private static long toMinutes(long date) {
        return toSeconds(date) / 60L;
    }

    private static long toHours(long date) {
        return toMinutes(date) / 60L;
    }

    private static long toDays(long date) {
        return toHours(date) / 24L;
    }

    private static long toWeeks(long date) {
        return toDays(date) / 7L;
    }

    private static long toMonths(long date) {
        return toWeeks(date) / 4L;
    }

    private static long toYears(long date) {
        return toMonths(date) / 12L;
    }

    /**
     * #获取时间下添加月份的
     *
     * @param date
     * @param pattern
     * @param monthNum
     * @return
     * @Date 下午 14:29 2019/6/28 0028
     **/
    public static String addMonth(Date date, String pattern, int monthNum) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, monthNum);
        Date addMonthDate = calendar.getTime();
        return new SimpleDateFormat(pattern).format(addMonthDate);
    }

    /**
     * #给时间添加分钟数
     *
     * @param date
     * @param minute
     * @return
     * @Date 上午 11:09 2019/8/9 0009
     **/
    public static Date addMinute(Date date, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, minute);
        return calendar.getTime();
    }

    /**
     * 时间转化成 String 格式的时间
     *
     * @param dateFormat
     * @param millSec
     * @return
     */
    public static String transferLongToDate(String dateFormat, Long millSec) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String millSecStr = millSec + "000";
        Date date = new Date(Long.valueOf(millSecStr));
        String resDate = sdf.format(date);
        return resDate;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past 天数
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        return SHORT_DATE.format(today);
    }

    /**
     * 获取过去第几年的日期
     */
    public static String getPastYear(int past) {
        SimpleDateFormat format = new SimpleDateFormat(SHORT_DATE_FORMAT_STR);
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, -past);
        Date y = c.getTime();
        String year = format.format(y);
        return year;
    }

    /**
     * #开始日期到结束日期的列表
     *
     * @param startDate
     * @param endDate
     * @return
     * @Date 下午 13:42 2019/12/25 0025
     **/
    public static List<String> getDayList(Date startDate, Date endDate) {
        if (endDate.before(startDate)) {
            return new ArrayList<>();
        }
        int days = DateUtils.differentDays(endDate, startDate);
        List<String> dayList = new ArrayList<>(days + 1);
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        for (int i = 0; i <= days; i++) {
            String date = DateUtils.toDateStr(cal.getTime());
            dayList.add(date);
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return dayList;
    }

    /**
     * #开始日期到结束日期的XX月XX日列表
     *
     * @param startDate
     * @param endDate
     * @return
     * @Date 下午 13:50 2019/12/25 0025
     **/
    public static List<String> getMonthDayList(Date startDate, Date endDate) {
        if (endDate.before(startDate)) {
            return new ArrayList<>();
        }
        int days = DateUtils.differentDays(endDate, startDate);
        List<String> dayList = new ArrayList<>(days + 1);
        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        for (int i = 0; i <= days; i++) {
            String date = DateUtils.format(cal.getTime(), "MM月dd日");
            dayList.add(date);
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        return dayList;
    }
}
